#include "G4SystemOfUnits.hh"
#include "Randomize.hh"
#include "G4ParticleTable.hh"
#include "G4UImanager.hh"
#include <memory>

#include "MyGenCreator.hh"

#include "GPSFromMAC.hh"

GPSFromMAC::GPSFromMAC(): MyBaseGen()
{
    m_PGType = "GPS from MAC file";
    m_ClassName = "GPSFromMAC";
    m_TypeFlag = 1;
    m_EvtFlag = 0;

    m_Particle = "gamma";
    m_ParticleEnergy = 1. * MeV;
    m_ParticlePosition = G4ThreeVector(0., 0., 0.);
    m_ParticlePolarization = G4ThreeVector(0., 0., 1.);
    m_ParticleMomentumDirection = G4ThreeVector(0., 0., 0.);

    m_GPS = nullptr;
}

GPSFromMAC::~GPSFromMAC()
{
    if(!m_GPS)
        delete m_GPS;
}

void GPSFromMAC::Initialize(YAML::Node yamlNode)
{
    m_GPS = new G4GeneralParticleSource();
    std::string MACFile = yamlNode["MACFile"].as<std::string>("GPS.mac");
    G4UImanager *UImanager = G4UImanager::GetUIpointer();

    std::string command = "/control/execute ";
    UImanager->ApplyCommand(command + MACFile);
}

void GPSFromMAC::GeneratePrimaryVertex(G4Event* anEvent)
{
    m_GPS->GeneratePrimaryVertex(anEvent);
    ++m_EvtFlag;
    m_Particle = m_GPS->GetParticleDefinition()->GetParticleName();
    m_ParticleEnergy = m_GPS->GetParticleEnergy() / MeV;
    m_ParticlePosition = m_GPS->GetParticlePosition() / mm;
    m_ParticlePolarization = m_GPS->GetParticlePolarization();
    m_ParticleMomentumDirection = m_GPS->GetParticleMomentumDirection();
}

REGISTGPSGEN(GPSFromMAC)